package com.example.demo.thread.ch5;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: htc
 * @date: Created in 11:04 2019/1/14.
 */
public class ConditionUsage {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private static boolean OK = false;

    public void aGuaredMethod() throws InterruptedException {
        lock.lock();
        try {
            while (OK){
                //当保护条件不成立，执行等待
                condition.await();
            }
            //执行目标动作
            doAction();
        } finally {
            lock.unlock();
        }
    }

    private void doAction(){}

    public void anNotificationMethod(){
        lock.lock();
        try {
            //更新共享变量
            changeState();
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    private void changeState(){}
}
